<?php


namespace App\Http\Controllers\Api;

use App\Services\Business\Models\Favorite;
use App\Services\Business\Interfaces\CourseServiceInterface;
use App\Services\Business\Services\BusinessService;
use App\Services\Business\Services\ArticleService;
use App\Services\Business\Interfaces\ArticleServiceInterface;
use App\Services\Business\Services\VideoService;
use App\Services\Business\Interfaces\VideoServiceInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class FavoriteController extends BaseController
{
    /**
     * @var CourseService
     */
    protected $courseService;
    /**
     * @var VideoService
     */
    protected $videoService;
    /**
     * @var ArticleService
     */
    protected $articleService;

    public function __construct(
        CourseServiceInterface        $courseService,
        ArticleServiceInterface       $articleService,
        VideoServiceInterface         $videoService

    )
    {
        $this->courseService = $courseService;
        $this->videoService = $videoService;
        $this->articleService =$articleService;

    }


    /**
     * @param Request $request
     * @param string $type
     * @param int $id
     * @return JsonResponse
     */
    public  function  favorite(Request $request, string $type, int $id){

        $category_id  = $request->input('categoryId',0);

        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal =  new $modal;
        $resource = $modal::find($id);
        $title = $resource->title;
        $userId =Auth::id();
        if ($resource->favorites()->where('user_id',$userId)->exists()){
            $resource->favorites()->where('user_id',$userId)->delete();
            $resource->decrement('favorite_count');
            return   $this->success(__('取消收藏'));

        }else{

            $favorite = new Favorite(['user_id'=>Auth::id(),'category_id'=>$category_id,'title'=>$title]);
            $resource->favorites()->save($favorite);
            $resource->increment('favorite_count');
            return    $this->success(__('收藏成功'));

        }



    }




}